<template>
  <div class="uuid-management">
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="openDialog('add')">新增UUID</el-button>
        <el-button type="primary" icon="Document" @click="showApiDoc">接口文档</el-button>
        <el-button type="success" icon="Download" @click="exportToExcel">导出Excel</el-button>
        <el-button type="warning" icon="Refresh" @click="handleResetDailyAccess">重置当日访问次数</el-button>
            <!-- 搜索框 -->
    <div class="search-box" style="margin-left: 20px;">
      <el-input
        v-model="searchQuery"
        placeholder="输入UUID进行搜索"
        style="width: 15vw; margin-right: 10px"
        @input="handleSearch"
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
    </div>
      </div>
      <!-- UUID列表 -->
      <el-table 
        :data="tableData" 
        border 
        stripe 
        @sort-change="handleSortChange"
        :default-sort="{prop: 'expireTime', order: 'ascending'}"
      >
        <el-table-column label="UUID" min-width="180">
          <template #default="scope">
            <div class="uuid-cell">
              <el-tooltip
                :content="isUUIDVisible[scope.row.uuid] ? scope.row.uuid : '复制'"
                placement="top"
              >
                <span class="uuid-text" @click="copyUUID(scope.row.uuid)">
                  {{ formatUUID(scope.row.uuid, isUUIDVisible[scope.row.uuid]) }}
                </span>
              </el-tooltip>
              <el-button
                :icon="isUUIDVisible[scope.row.uuid] ? 'View' : 'Hide'"
                link
                @click="toggleUUIDVisibility(scope.row.uuid)"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="CreatedAt" min-width="180" sortable>
          <template #default="scope">
            {{ formatDate(scope.row.CreatedAt) }}
          </template>
        </el-table-column>
        <el-table-column label="过期时间" prop="expireTime" min-width="180" sortable="custom">
          <template #default="scope">
            {{ formatDate(scope.row.expireTime) }}
            <div class="remaining-time">
              剩余：{{ calculateRemainingTime(scope.row.expireTime) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" min-width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isActive ? 'success' : 'danger'">
              {{ scope.row.isActive ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="每日访问限制" prop="dailyAccessLimit" min-width="120" sortable />
        <el-table-column label="当日访问次数" prop="currentDayAccess" min-width="120" sortable />
        <el-table-column label="总访问限制" prop="totalAccessLimit" min-width="120" sortable />
        <el-table-column label="总访问次数" prop="totalAccess" min-width="120" sortable />
        <el-table-column label="描述" prop="description" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button type="primary" link icon="edit" @click="openDialog('edit', scope.row)">编辑</el-button>
            <el-button type="primary" link icon="delete" @click="handleDelete(scope.row)">删除</el-button>
            <el-button type="primary" link icon="Check" @click="testUUID(scope.row)">测试</el-button>
            <el-button type="primary" link icon="timer" @click="openRenewDialog(scope.row)">续费</el-button>
            <el-button type="primary" link icon="List" @click="viewRenewalHistory(scope.row)">历史</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="gva-pagination">
        <el-pagination
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增UUID' : '编辑UUID'"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="UUID" prop="uuid" v-if="dialogType === 'add'">
          <div class="uuid-input-group">
            <el-input 
              v-model="form.uuid" 
              :placeholder="form.isManualUUID ? '请输入UUID' : '自动生成的UUID'"
              :disabled="!form.isManualUUID"
            />
            <el-button @click="toggleUUIDMode">
              {{ form.isManualUUID ? '自动生成' : '手动输入' }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="过期时间" prop="expireTime">
          <div class="expire-time-group">
            <div class="month-input-group" v-if="!form.isCustomMonth">
              <el-select v-model="form.selectedMonths" placeholder="选择授权时长" @change="handleMonthsChange" style="width: 180px">
                <el-option v-for="i in 60" :key="i" :label="`${i}个月`" :value="i" />
              </el-select>
            </div>
            <div class="month-input-group" v-else>
              <el-input-number 
                v-model="form.customMonths" 
                :min="1" 
                :max="60" 
                placeholder="输入月数"
                @change="handleCustomMonthsChange"
                style="width: 180px"
              />
            </div>
            <el-button @click="toggleMonthInputMode">
              {{ form.isCustomMonth ? '选择月份' : '自定义月份' }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="isActive">
          <el-switch v-model="form.isActive" />
        </el-form-item>
        <el-form-item label="每日访问限制" prop="dailyAccessLimit">
          <el-input-number v-model="form.dailyAccessLimit" :min="1" :max="10000" />
        </el-form-item>
        <el-form-item label="总访问限制" prop="totalAccessLimit">
          <el-input-number v-model="form.totalAccessLimit" :min="1" :max="1000000" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入描述信息"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- API文档对话框 -->
    <ApiDoc :visible="apiDocVisible" @update:visible="(val) => apiDocVisible = val" />

    <!-- 续费对话框 -->
    <el-dialog
      title="UUID续费"
      v-model="renewDialogVisible"
      width="500px"
    >
      <el-form ref="renewFormRef" :model="renewForm" :rules="renewRules" label-width="120px">
        <el-form-item label="UUID">
          <span>{{ renewForm.uuid }}</span>
        </el-form-item>
        <el-form-item label="当前过期时间">
          <span>{{ formatDate(renewForm.currentExpireTime) }}</span>
          <div class="remaining-time">
            剩余：{{ calculateRemainingTime(renewForm.currentExpireTime) }}
            <el-tooltip v-if="isExpired(renewForm.currentExpireTime)" effect="dark" content="已过期，将从当前日期开始计算新的过期时间" placement="top">
              <el-tag type="danger" size="small" style="margin-left: 5px">已过期</el-tag>
            </el-tooltip>
          </div>
        </el-form-item>
        <el-form-item label="续费方式" prop="renewType">
          <el-radio-group v-model="renewForm.renewType" @change="handleRenewTypeChange">
            <el-radio :label="'day'">按天</el-radio>
            <el-radio :label="'month'">按月</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="renewForm.renewType === 'day' ? '续费天数' : '续费月数'" prop="renewValue">
          <el-input-number 
            v-model="renewForm.renewValue" 
            :min="1" 
            :max="renewForm.renewType === 'day' ? 365 : 60" 
            @change="calculateNewExpireTime"
          />
        </el-form-item>
        <el-form-item label="新过期时间">
          <span>{{ formatDate(renewForm.newExpireTime) }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="renewDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRenew">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 续费历史对话框 -->
    <el-dialog
      title="UUID续费历史"
      v-model="renewalHistoryDialogVisible"
      width="800px"
    >
      <div class="renewal-summary" v-if="renewalHistory.length > 0">
        <el-alert
          title=""
          type="info"
          :closable="false"
        >
          <template #default>
            <div class="renewal-count">
              <span><strong>总续费次数：</strong>{{ renewalHistory.length }}次</span>
            </div>
            <div class="renewal-count" style="margin-top: 8px;">
              <span><strong>总续费天数：</strong>{{ calculateTotalRenewalDays() }}天</span>
            </div>
          </template>
        </el-alert>
      </div>
      <div v-if="renewalHistory.length === 0" class="empty-data">
        <el-empty description="暂无续费记录" />
      </div>
      <el-table v-else :data="renewalHistory" border stripe>
        <el-table-column label="UUID" prop="uuid" min-width="180" show-overflow-tooltip />
        <el-table-column label="续费类型" min-width="100">
          <template #default="scope">
            {{ scope.row.renewalType === 'day' ? '按天' : '按月' }}
          </template>
        </el-table-column>
        <el-table-column label="续费值" prop="renewalValue" min-width="80">
          <template #default="scope">
            {{ scope.row.renewalValue }} {{ scope.row.renewalType === 'day' ? '天' : '个月' }}
          </template>
        </el-table-column>
        <el-table-column label="原过期时间" min-width="180">
          <template #default="scope">
            {{ formatDate(scope.row.oldExpireTime) }}
          </template>
        </el-table-column>
        <el-table-column label="新过期时间" min-width="180">
          <template #default="scope">
            {{ formatDate(scope.row.newExpireTime) }}
          </template>
        </el-table-column>
        <el-table-column label="续费时间" min-width="180">
          <template #default="scope">
            {{ formatDate(scope.row.CreatedAt) }}
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" min-width="150" show-overflow-tooltip />
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="renewalHistoryDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDate } from '@/utils/format'
import { getUUIDList, createUUID, updateUUID, deleteUUID, validateUUID, renewUUID, getUUIDRenewalRecords, getUUIDExportData, resetDailyAccess } from '@/api/uuidLicense'
import * as XLSX from 'xlsx'
import { v4 as uuidv4 } from 'uuid'
import { View, Hide, Check, Document, Timer, List, Download, Refresh } from '@element-plus/icons-vue'
import ApiDoc from './components/ApiDoc.vue'

export default {
  name: 'UUIDManagement',
  components: {
    View,
    Hide,
    Check,
    Document,
    Timer,
    List,
    Download,
    Refresh,
    ApiDoc
  },
  setup() {
    // 表格数据
    const tableData = ref([])
    const page = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const sortBy = ref('')
    const sortOrder = ref('')

    // 对话框控制
    const dialogVisible = ref(false)
    const dialogType = ref('add')
    const formRef = ref(null)

    // 表单数据
    const form = ref({
      uuid: '',
      expireTime: '',
      selectedMonths: null,
      customMonths: null,
      isActive: true,
      dailyAccessLimit: 10000,
      totalAccessLimit: 10000,
      description: '',
      isManualUUID: true,
      isCustomMonth: false
    })

    // UUID验证规则
    const uuidPattern = /^.{36}$/

    // 验证UUID格式
    const validateUUIDFormat = (rule, value, callback) => {
      if (!value && !form.value.isManualUUID) {
        callback()
        return
      }
      if (!value) {
        callback(new Error('请输入UUID'))
        return
      }
      if (!uuidPattern.test(value)) {
        callback(new Error('UUID长度必须为36位'))
        return
      }
      callback()
    }

    // 表单验证规则
    const rules = {
      uuid: [
        { validator: validateUUIDFormat, trigger: 'blur' }
      ],
      expireTime: [
        { required: true, message: '请选择过期时间', trigger: 'blur' }
      ],
      dailyAccessLimit: [
        { required: true, message: '请设置每日访问限制', trigger: 'blur' }
      ],
      totalAccessLimit: [
        { required: true, message: '请设置总访问限制', trigger: 'blur' }
      ]
    }

    // UUID显示控制
    const isUUIDVisible = reactive({})

    // 格式化UUID显示
    const formatUUID = (uuid, isVisible) => {
      if (isVisible) {
        return uuid
      }
      if (!uuid) return ''
      return `${uuid.slice(0, 8)}...${uuid.slice(-8)}`
    }

    // 复制UUID
    const copyUUID = async (uuid) => {
      try {
        await navigator.clipboard.writeText(uuid)
        ElMessage.success('UUID已复制到剪贴板')
      } catch (err) {
        console.error(err)
        ElMessage.error('复制失败')
      }
    }

    // 切换UUID可见性
    const toggleUUIDVisibility = (uuid) => {
      isUUIDVisible[uuid] = !isUUIDVisible[uuid]
    }

    // 获取UUID列表
    const searchQuery = ref('')
    const getTableData = async () => {
      const params = {
        page: page.value,
        pageSize: pageSize.value,
        keyword: searchQuery.value
      }
      
      // 添加排序参数
      if (sortBy.value && sortOrder.value) {
        params.sort = sortBy.value
        params.order = sortOrder.value
      }
      
      try {
        const res = await getUUIDList(params)
        if (res.code === 0) {
          tableData.value = res.data.list
          total.value = res.data.total
        }
      } catch (err) {
        console.error(err)
      }
    }
    
    // 处理表格排序变化
    const handleSortChange = ({ prop, order }) => {
      if (prop && order) {
        // 将前端属性名转换为后端字段名
        const propMapping = {
          'dailyAccessLimit': 'daily_access_limit',
          'currentDayAccess': 'current_day_access',
          'totalAccessLimit': 'total_access_limit',
          'totalAccess': 'total_access',
          'CreatedAt': 'created_at',
          'expireTime': 'expire_time'
        };
        
        sortBy.value = propMapping[prop] || prop;
        sortOrder.value = order === 'ascending' ? 'asc' : 'desc';
      } else {
        sortBy.value = '';
        sortOrder.value = '';
      }
      
      getTableData();
    }

    // 生成新的UUID
    const generateNewUUID = () => {
      return uuidv4().toUpperCase()
    }

    // 计算剩余时间
    const calculateRemainingTime = (expireTime) => {
      const now = new Date()
      const expireDate = new Date(expireTime)
      if (expireDate <= now) {
        return '已过期'
      }

      const diffTime = expireDate - now
      const days = Math.floor(diffTime / (1000 * 60 * 60 * 24))
      const months = Math.floor(days / 30)
      const remainingDays = days % 30

      if (months > 0) {
        return `${months}个月${remainingDays}天`
      }
      return `${remainingDays}天`
    }

    // 判断UUID是否已过期
    const isExpired = (expireTime) => {
      const now = new Date()
      const expireDate = new Date(expireTime)
      return expireDate <= now
    }

    // 处理月份选择变化
    const handleMonthsChange = (months) => {
      if (!months) return
      form.value.customMonths = null
      const now = new Date()
      const expireDate = new Date(now)
      expireDate.setMonth(expireDate.getMonth() + months)
      form.value.expireTime = expireDate.getTime()
    }

    // 处理自定义月份变化
    const handleCustomMonthsChange = (months) => {
      if (!months) return
      form.value.selectedMonths = null
      const now = new Date()
      const expireDate = new Date(now)
      expireDate.setMonth(expireDate.getMonth() + months)
      form.value.expireTime = expireDate.getTime()
    }

    // 切换月份输入模式
    const toggleMonthInputMode = () => {
      form.value.isCustomMonth = !form.value.isCustomMonth
      form.value.selectedMonths = null
      form.value.customMonths = null
      form.value.expireTime = new Date().getTime() // 重置为当前时间
    }

    // 打开对话框
    const openDialog = (type, row) => {
      dialogType.value = type
      dialogVisible.value = true
      if (type === 'add') {
        form.value = {
          uuid: '',
          expireTime: new Date().getTime(),
          selectedMonths: 1,
          customMonths: null,
          isActive: true,
          dailyAccessLimit: 10000,
          totalAccessLimit: 10000,
          description: '',
          isManualUUID: true,
          isCustomMonth: false
        }
        // 初始化时自动设置一个月的过期时间
        handleMonthsChange(1)
      } else {
        const editData = JSON.parse(JSON.stringify(row))
        editData.expireTime = new Date(editData.expireTime).getTime()
        editData.isManualUUID = true
        editData.selectedMonths = null
        editData.customMonths = null
        editData.isCustomMonth = false
        form.value = editData
      }
    }

    // 切换UUID输入模式
    const toggleUUIDMode = () => {
      form.value.isManualUUID = !form.value.isManualUUID
      if (!form.value.isManualUUID) {
        form.value.uuid = generateNewUUID()
      }
    }

    // 提交前处理UUID
    const handleSubmit = async () => {
      if (!formRef.value) return
      await formRef.value.validate(async (valid) => {
        if (valid) {
          // 如果是手动输入的UUID，转换为大写
          if (form.value.isManualUUID) {
            form.value.uuid = form.value.uuid.toUpperCase()
          }
          
          try {
            const api = dialogType.value === 'add' ? createUUID : updateUUID
            const res = await api(form.value)
            if (res.code === 0) {
              ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
              dialogVisible.value = false
              getTableData()
            }
          } catch (err) {
            console.error(err)
            ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败')
          }
        }
      })
    }

    // 删除UUID
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确定要删除该UUID吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await deleteUUID(row.uuid)
        ElMessage.success('删除成功')
        getTableData()
      } catch (err) {
        console.error(err)
        if (err !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    // 导出Excel
    const exportToExcel = async () => {
      try {
        ElMessage.info('正在导出数据，请稍候...')
        
        // 获取所有数据（设置较大的pageSize）
        const params = {
          page: 1,
          pageSize: 10000, // 设置一个足够大的数字，获取所有数据
          keyword: searchQuery.value,
          sort: sortBy.value,
          order: sortOrder.value
        }
        
        // 使用新的API获取导出数据，包含续费信息
        const res = await getUUIDExportData(params)
        if (!res.data?.list || res.data.list.length === 0) {
          ElMessage.warning('没有数据可供导出')
          return
        }
        
        // 准备Excel数据
        const excelData = res.data.list.map(item => {
          // 计算剩余时间
          let remainingTime = ''
          const now = new Date()
          const expireTime = new Date(item.expireTime)
          
          if (now > expireTime) {
            remainingTime = '已过期'
          } else {
            const diffTime = expireTime - now
            const days = Math.floor(diffTime / (1000 * 60 * 60 * 24))
            const months = Math.floor(days / 30)
            const remainingDays = days % 30
            
            if (months > 0) {
              remainingTime = `${months}个月${remainingDays}天`
            } else {
              remainingTime = `${remainingDays}天`
            }
          }
          
          // 返回格式化的数据（加入续费信息）
          return {
            'UUID': item.uuid,
            '创建时间': formatDate(item.CreatedAt),
            '过期时间': formatDate(item.expireTime),
            '剩余时间': remainingTime,
            '是否激活': item.isActive ? '是' : '否',
            '每日访问限制': item.dailyAccessLimit,
            '当日访问次数': item.currentDayAccess,
            '总访问限制': item.totalAccessLimit,
            '总访问次数': item.totalAccess,
            '总续费次数': item.renewalCount || 0,
            '总续费天数': item.totalRenewalDays || 0,
            '最近续费时间': item.lastRenewalTime ? formatDate(item.lastRenewalTime) : '无',
            '描述': item.description
          }
        })
        
        // 创建工作簿和工作表
        const worksheet = XLSX.utils.json_to_sheet(excelData)
        const workbook = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(workbook, worksheet, 'UUID列表')
        
        // 设置列宽
        const colWidths = [
          { wch: 40 }, // UUID
          { wch: 20 }, // 创建时间
          { wch: 20 }, // 过期时间
          { wch: 15 }, // 剩余时间
          { wch: 10 }, // 是否激活
          { wch: 15 }, // 每日访问限制
          { wch: 15 }, // 当日访问次数
          { wch: 15 }, // 总访问限制
          { wch: 15 }, // 总访问次数
          { wch: 12 }, // 总续费次数
          { wch: 12 }, // 总续费天数
          { wch: 20 }, // 最近续费时间
          { wch: 40 }  // 描述
        ]
        worksheet['!cols'] = colWidths
        
        // 生成文件名
        const now = new Date()
        const timestamp = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}_${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}`
        const fileName = `UUID列表_${timestamp}.xlsx`
        
        // 下载文件
        XLSX.writeFile(workbook, fileName)
        
        ElMessage.success('导出成功')
      } catch (err) {
        console.error('导出失败:', err)
        ElMessage.error('导出失败: ' + (err.message || '未知错误'))
      }
    }

    // 重置当日访问次数
    const handleResetDailyAccess = async () => {
      try {
        await ElMessageBox.confirm(
          '此操作将重置所有UUID的当日访问次数，是否继续？',
          '确认重置',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        
        await resetDailyAccess()
        ElMessage.success('重置成功')
        getTableData() // 刷新数据
      } catch (err) {
        if (err !== 'cancel') {
          ElMessage.error('重置失败: ' + (err.message || '未知错误'))
        }
      }
    }

    // 分页处理
    const handleSizeChange = (val) => {
      pageSize.value = val
      getTableData()
    }

    const handleCurrentChange = (val) => {
      page.value = val
      getTableData()
    }

    // 测试UUID
    const testUUID = async (row) => {
      try {
        ElMessage.info('正在测试UUID...')
        const res = await validateUUID(row.uuid)
        if (res.code === 0) {
          const expiryMessage = res.data || '未知'
          ElMessage.success(`UUID验证通过，${expiryMessage}`)
          // 刷新数据以更新使用次数
          await getTableData()
        } else {
          ElMessage.error(res.msg || 'UUID验证失败')
        }
      } catch (err) {
        console.error(err)
        ElMessage.error('测试失败')
      }
    }

    // API文档对话框控制
    const apiDocVisible = ref(false)
    const showApiDoc = () => {
      apiDocVisible.value = true
    }
    
    // 续费对话框控制
    const renewDialogVisible = ref(false)
    const renewFormRef = ref(null)
    const renewForm = ref({
      uuid: '',
      currentExpireTime: 0,
      renewType: 'month', // 'day' 或 'month'
      renewValue: 1,
      newExpireTime: 0
    })
    
    // 续费表单验证规则
    const renewRules = {
      renewType: [
        { required: true, message: '请选择续费方式', trigger: 'change' }
      ],
      renewValue: [
        { required: true, message: '请输入续费时长', trigger: 'blur' },
        { type: 'number', min: 1, message: '续费时长必须大于0', trigger: 'blur' }
      ]
    }
    
    // 打开续费对话框
    const openRenewDialog = (row) => {
      renewForm.value = {
        uuid: row.uuid,
        currentExpireTime: new Date(row.expireTime).getTime(),
        renewType: 'month',
        renewValue: 1,
        newExpireTime: 0
      }
      calculateNewExpireTime()
      renewDialogVisible.value = true
    }
    
    // 续费历史对话框控制
    const renewalHistoryDialogVisible = ref(false)
    const renewalHistory = ref([])

    const viewRenewalHistory = async (row) => {
      renewalHistoryDialogVisible.value = true
      // 获取续费历史
      try {
        const res = await getUUIDRenewalRecords(row.uuid)
        if (res.code === 0) {
          renewalHistory.value = res.data
        } else {
          ElMessage.error(res.msg || '获取续费历史失败')
        }
      } catch (err) {
        console.error(err)
        ElMessage.error('获取续费历史失败')
      }
    }

    // 处理续费类型变化
    const handleRenewTypeChange = () => {
      renewForm.value.renewValue = 1
      calculateNewExpireTime()
    }
    
    // 计算总的续费天数
    const calculateTotalRenewalDays = () => {
      if (!renewalHistory.value || renewalHistory.value.length === 0) {
        return 0
      }
      
      return renewalHistory.value.reduce((total, record) => {
        if (record.renewalType === 'day') {
          // 如果是按天续费，直接加上天数
          return total + record.renewalValue
        } else {
          // 如果是按月续费，将月转换为天 (按每月30天计算)
          return total + (record.renewalValue * 30)
        }
      }, 0)
    }
    
    // 计算总的续费月数
    const calculateTotalRenewalMonths = () => {
      if (!renewalHistory.value || renewalHistory.value.length === 0) {
        return 0
      }
      
      // 计算总月数，按天数除以30取两位小数
      const totalDays = calculateTotalRenewalDays()
      return (totalDays / 30).toFixed(1)
    }
    
    // 计算续费总金额 (假设每月30元)
    const calculateTotalRenewalAmount = () => {
      if (!renewalHistory.value || renewalHistory.value.length === 0) {
        return 0
      }
      
      // 月费率：30元/月
      const monthlyRate = 30
      // 日费率：1元/天
      const dailyRate = 1
      
      return renewalHistory.value.reduce((total, record) => {
        if (record.renewalType === 'day') {
          // 如果是按天续费
          return total + (record.renewalValue * dailyRate)
        } else {
          // 如果是按月续费
          return total + (record.renewalValue * monthlyRate)
        }
      }, 0)
    }
    
    // 计算新的过期时间
    const calculateNewExpireTime = () => {
      const currentExpireDate = new Date(renewForm.value.currentExpireTime)
      const now = new Date()
      
      // 判断是否已过期
      const isExpired = currentExpireDate < now
      
      // 如果已过期，则从当前日期计算；否则从原过期时间计算
      let baseDate = isExpired ? now : currentExpireDate
      const newExpireDate = new Date(baseDate)
      
      if (renewForm.value.renewType === 'day') {
        newExpireDate.setDate(newExpireDate.getDate() + renewForm.value.renewValue)
      } else { // month
        newExpireDate.setMonth(newExpireDate.getMonth() + renewForm.value.renewValue)
      }
      
      renewForm.value.newExpireTime = newExpireDate.getTime()
    }
    
    // 处理续费提交
    const handleRenew = async () => {
      if (!renewFormRef.value) {
        console.error('renewFormRef不存在')
        return
      }
      
      try {
        const valid = await renewFormRef.value.validate()
        if (valid) {
          try {
            const data = {
              uuid: renewForm.value.uuid,
              renewType: renewForm.value.renewType,
              renewValue: parseInt(renewForm.value.renewValue)
            }
            
            console.log('续费请求参数:', JSON.stringify(data))
            
            const res = await renewUUID(data)
            console.log('续费响应:', res)
            
            if (res.code === 0) {
              ElMessage.success('续费成功')
              renewDialogVisible.value = false
              getTableData() // 刷新表格数据
            } else {
              console.error('续费失败响应:', res)
              ElMessage.error('续费失败: ' + (res.msg || '未知错误'))
            }
          } catch (err) {
            console.error('续费请求错误:', err)
            if (err.response) {
              console.error('错误响应:', err.response)
            }
            ElMessage.error('续费失败: ' + (err.message || '未知错误'))
          }
        } else {
          console.error('表单验证失败')
        }
      } catch (validationError) {
        console.error('表单验证抛出错误:', validationError)
      }
    }

    // 处理搜索
    const handleSearch = () => {
      page.value = 1 // 重置页码
      getTableData()
    }

    // 监听搜索框输入
    watch(searchQuery, (newVal) => {
      if (!newVal) {
        // 当搜索框清空时，重新加载数据
        handleSearch()
      }
    })

    onMounted(() => {
      getTableData()
    })

    return {
      tableData,
      page,
      pageSize,
      total,
      dialogVisible,
      dialogType,
      formRef,
      form,
      rules,
      formatDate,
      openDialog,
      handleSubmit,
      handleDelete,
      handleSizeChange,
      handleCurrentChange,
      formatUUID,
      copyUUID,
      toggleUUIDVisibility,
      isUUIDVisible,
      testUUID,
      apiDocVisible,
      showApiDoc,
      toggleUUIDMode,
      calculateRemainingTime,
      isExpired,
      handleMonthsChange,
      handleCustomMonthsChange,
      toggleMonthInputMode,
      searchQuery,
      handleSearch,
      handleSortChange,
      sortBy,
      sortOrder,
      exportToExcel,
      handleResetDailyAccess,
      // 续费相关
      renewDialogVisible,
      renewFormRef,
      renewForm,
      renewRules,
      openRenewDialog,
      handleRenewTypeChange,
      calculateNewExpireTime,
      handleRenew,
      // 续费历史相关
      renewalHistoryDialogVisible,
      renewalHistory,
      viewRenewalHistory,
      // 续费统计计算函数
      calculateTotalRenewalDays,
      calculateTotalRenewalMonths,
      calculateTotalRenewalAmount
    }
  }
}
</script>

<style lang="scss" scoped>
.uuid-management {
  background-color: #fff;
  padding: 20px;
  
  .gva-btn-list {
    margin-bottom: 12px;
  }
  
  .gva-pagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 12px;
  }
  
  .dialog-footer {
    padding-top: 20px;
    text-align: right;
  }
  
  .uuid-cell {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .uuid-text {
      cursor: pointer;
      &:hover {
        color: var(--el-color-primary);
      }
    }
  }
  
  .uuid-input-group {
    display: flex;
    gap: 8px;
    
    .el-input {
      flex: 1;
    }
  }

  .expire-time-group {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .remaining-time {
    font-size: 12px;
    color: #666;
    margin-top: 4px;
  }
  
  .renewal-summary {
    margin-bottom: 15px;
  }
  
  .renewal-count {
    font-size: 14px;
    display: flex;
    justify-content: space-between;
    strong {
      font-weight: 600;
    }
  }

  .search-box {
    display: flex;
    align-items: center;
    margin: 20px 0;
  }

  .empty-data {
    padding: 20px;
    text-align: center;
  }
}
</style>